<template>
	<div>
		<base-modal :title="title" :show.sync="dialogVisible" width="500px" @close="closeDialog">
			<el-form
				class="pad-16"
				:model="ruleForm"
				ref="ruleFormDom"
				label-position="top"
				:rules="rules"
				v-loading="loading"
			>
				<el-form-item :label="$t('faultLibrary.faultObject.label5')" prop="iconList">
					<div class="icon-file">
						<UploadIcon
							ref="uploadIconDom"
							:value="ruleForm.attribute.iconImg.fileArr"
							@input="v => (ruleForm.attribute.iconImg.fileArr = v)"
						></UploadIcon>
						<el-button type="text" @click="editIcon">{{ $t('faultLibrary.faultObject.btn1') }}</el-button>
					</div>
				</el-form-item>

				<el-form-item :label="$t('common.base.title')" prop="faultDesc">
					<div style="display: flex;">
						<el-input
							v-model="ruleForm.faultDesc"
							:maxlength="100"
							:placeholder="$t('common.placeholder.input2')"
							@blur="ruleForm.faultDesc = ruleForm.faultDesc.trim()"
						>
						</el-input>
					</div>
					
				</el-form-item>

				<el-form-item :label="$t('faultLibrary.faultObject.label1')" prop="faultContent">
					<div style="display: flex;">
						<el-input
							type="textarea"
							v-model="ruleForm.faultContent"
							:maxlength="5000"
							:placeholder="$t('common.base.tip.defaultPlaceholder')"
							:autosize="{ minRows: 2, maxRows: 6 }"
							@blur="ruleForm.faultContent = ruleForm.faultContent.trim()"
						>
						</el-input>
					</div>
					
				</el-form-item>

				<el-form-item
					:label="$t('faultLibrary.faultObject.label7')"
					prop="isCorrelationObj"
					:rules="[{ required: ruleForm.isCorrelationObj, message: '', trigger: 'change' }]"
				>
					<el-switch v-model="ruleForm.isCorrelationObj" @change="isCorrelationChange"></el-switch>
				</el-form-item>

				<template v-if="ruleForm.isCorrelationObj">
					<!-- 关联对象 -->
					<el-form-item
						label=""
						prop="relType"
						:rules="[{ required: true, message: $t('common.base.pleaseSelect'), trigger: 'change' }]"
					>
						<el-radio-group v-model="ruleForm.relType" @input="relTypeChange">
							<el-radio :label="1">{{ $t('common.base.product') }}</el-radio>
							<el-radio :label="2" v-if="isCloudWarehouse">{{ $t('common.form.type.material') }}</el-radio>
							<el-radio :label="3" v-if="!isCloudWarehouse">{{ $t('common.base.sparePart') }}</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item
						label=""
						prop="relObj"
						:rules="[{ required: true, type: 'array', message: $t('common.base.pleaseSelect'), trigger: 'change' }]"
					>
						<CorrelationObjSelect
							v-if="dialogVisible"
							ref="relationObjRef"
							v-model="ruleForm.relObj"
							:rel-type="ruleForm.relType"
						/>
					</el-form-item>
				</template>

				<!-- 自定义标签 -->
				<el-form-item v-else :label="$t('common.base.classification')">
					<div style="display: flex;">
						<el-input
							:maxlength="20"
							v-model="ruleForm.faultLabel"
							:placeholder="$t('common.faultLibrary.classificationPlaceholder')"
							@blur="ruleForm.faultLabel = ruleForm.faultLabel.trim()"
						>
						</el-input>
					</div>
				</el-form-item>

				<el-form-item :label="$t('common.paas.formType.attachment')">
					<form-attachment :field="{ isNull: 1 }" v-model="ruleForm.attribute.attachment"></form-attachment>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">{{ $t('common.base.cancel') }}</el-button>
				<el-button type="primary" :loading="submitLoading" @click="submitForm">{{ $t('common.base.save') }}</el-button>
			</div>
		</base-modal>
		<base-modal :title="$t('faultLibrary.faultObject.label6')" :show.sync="showChooseIcon">
			<div class="pad-16">
				<div class="mar-b-12 mar-t-12">{{ $t('faultLibrary.faultObject.tips3') }}</div>
				<ChangeIcon ref="changeIconDom" @choose="chooseIcon"></ChangeIcon>
			</div>
			<!-- <div slot="footer" class="dialog-footer">
        <el-button @click="showChooseIcon = false">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">{{ $t('common.base.save') }}</el-button>
      </div> -->
		</base-modal>
	</div>
</template>

<script>
// 关联对象选择框
import CorrelationObjSelect from '@src/modules/faultLibrary/components/CorrelationObjSelect'
import ChangeIcon from '@src/modules/faultLibrary/components/FaultInformationDialog/changeIcon.vue'
import UploadIcon from '@src/modules/faultLibrary/components/FaultInformationDialog/uploadIcon.vue'
import { getRootWindow } from '@src/util/dom'
import i18n, { t } from '@src/locales'
import { cloneDeep } from 'lodash'

import { libraryCreate, libraryEdit, faultDetail } from '@src/api/Fault'
import { getListItem, validateFaultDesc } from './common'

const baseData = {
	// 级别，故障对象是写死的1
	faultLevel: 1,
	// 对象描述
	faultDesc: '',
	faultContent: '',
	// 是否关联对象
	isCorrelationObj: true,
	// 关联对象类型，默认产品
	relType: 1,
	// 关联的对象
	relObj: [],
	// 自定义标签
	faultLabel: '',
	attribute: {
		iconImg: {
			// 0 系统内置图片
			type: 0,
			//
			index: '',
			fileArr: [],
		},
		attachment: [],
	},
	descNameLanguage: {},
	contentNameLanguage: {},
	labelNameLanguage: {},
}
export default {
	name: 'FaultObj',

	data() {
		return {
			loading: false,
			// 获取服务对象列表loading
			objListLoading: false,

			options: [],
			ruleForm: cloneDeep(baseData),

			// 用于记录选中的关联对象的id和name ID：name
			relObjIdNameMap: {},
			submitLoading: false,
			rules: {
				faultDesc: [{ required: true, validator: validateFaultDesc, trigger: ['blur', 'change'] }],
				iconList: [
					{
						required: true,
						validator: (rule, value, callback) => {
							if (!this.ruleForm.attribute.iconImg.fileArr.length) {
								callback(new Error(t('common.placeholder.select')))
							} else {
								callback()
							}
						},
						trigger: ['blur', 'change'],
					},
				],
			},
			showChooseIcon: false,
			oldRelObj: [],
			// iconUrl: '',
		}
	},

	components: {
		CorrelationObjSelect,
		ChangeIcon,
		UploadIcon,
	},

	props: {
		value: {
			type: Boolean,
			default: false,
		},

		currentFaultObjId: {
			type: String,
			default: '',
		},

		// 来源：0:故障树创建（默认）   1:工单附加组件创建（工单附加组件）
		faultSource: {
			type: Number,
			default: 0,
		},
	},
	watch: {
		value(value) {
			if (!value) {
				this.initForm()
			}
		},
		dialogVisible(newValue) {
			if (newValue === true) {
				this.openDialog()
			}
		},
	},

	computed: {
		dialogVisible: {
			get() {
				return this.value
			},

			set(val) {
				this.$emit('input', val)
			},
		},

		title: {
			get() {
				return this.currentFaultObjId
					? this.$t('faultLibrary.faultObject.editTitle1')
					: this.$t('faultLibrary.faultObject.createBtn2')
			},
		},

		/**
		 * @description 是否开启云仓灰度
		 */
		isCloudWarehouse() {
			const RootWindow = getRootWindow(window)
			return RootWindow.grayAuth?.cloudwarehouse || false
		},
		iconUrl() {
			return getListItem(this.ruleForm.attribute.iconImg.index)
		},
	},

	methods: {
		initForm() {
			this.options = []
			this.ruleForm = cloneDeep(baseData)

			// 用于记录选中的关联对象的id和name ID：name
			this.relObjIdNameMap = {}
		},
		async openDialog() {
			// this.iconUrl = getListItem(this.ruleForm.iconImg.index);
			if (!this.currentFaultObjId) {
				return this.$nextTick(() => {
					this.$refs.uploadIconDom.setGoodsPicListBySystem(getListItem('0-0'))
				})
			}
			this.loading = true
			const res = await faultDetail({ faultId: this.currentFaultObjId })

			this.loading = false
			const { id, relType, relObj, faultLabel, faultDesc, products, faultContent, attribute } = res.data || {}

			// 编辑页面需要处理数据
			this.ruleForm.id = id
			// 没有父级，写死null
			this.ruleForm.parentId = null
			this.ruleForm.faultDesc = faultDesc
			this.ruleForm.relType = relType
			this.ruleForm.faultLabel = faultLabel
			this.ruleForm.faultContent = faultContent
			if (attribute) {
				this.ruleForm.attribute = attribute
				if (attribute.iconImg.index) {
					this.$nextTick(() => {
						// 兼容老数据
						this.$refs.uploadIconDom.setGoodsPicListBySystem(getListItem(attribute.iconImg.index))
					})
				}
			}

			// this.iconUrl = getListItem(this.ruleForm.iconImg.index);

			// // 当有故障对象时，需要将指定的故障对象的id和name存储起来,提交时需要返回对象
			if (relType) {
				this.ruleForm.relObj =
					relType === 1
						? relObj.map((i, index) => {
								const { relObjId, relObjName } = i
								const ids = products[index] || []
								return {
									key: relObjId,
									label: relObjName,
									keyArr: ids,
								}
						  })
						: (relObj || []).map(item => {
								return {
									// 备件列表的id是number类型
									id: relType === 2 ? Number(item.relObjId) : item.relObjId,
									name: item.relObjName,
									label: item.relObjName,
									value: relType === 2 ? Number(item.relObjId) : item.relObjId,
								}
						  })
				this.ruleForm.isCorrelationObj = true
			} else {
				// isCorrelationObj没有存储到数据库，需要前端自己计算
				this.ruleForm.isCorrelationObj = false
			}
		},

		closeDialog() {
			this.closeDialog = false
			this.$refs?.ruleFormDom.resetFields()
			this.$refs?.relationObjRef?.clearCascader()
		},

		isCorrelationChange() {
			// 切换关联对象，更改relType的值
			this.ruleForm.relType = this.ruleForm.isCorrelationObj ? 1 : 0
			this.ruleForm.relObj = []
			this.ruleForm.faultLabel = ''
			this.$refs.ruleFormDom.clearValidate()
		},

		submitForm() {
			try {
				this.$refs.ruleFormDom.validate(async valid => {
					if (!valid) return
					this.submitLoading = true
					const params = this.paramSubmitSwitch()

					const port = this.currentFaultObjId ? libraryEdit : libraryCreate
					const res = await port(params)

					if (res.status !== 0) {
						this.$notify.error({
							title: this.$t('common.base.toast'),
							message: res.message,
							duration: 2000,
						})
						return
					}
					this.dialogVisible = false
					this.$emit('operateSuc')
				})
			} catch (err) {
				console.log('submitForm => err', err)
				this.submitLoading = false
			} finally {
				this.submitLoading = false
			}
		},

		// 提交前，数据修改
		paramSubmitSwitch() {
			let params = { ...this.ruleForm }
			const { isCorrelationObj, relType } = params

			// 有关联对象,需要通过关联对象的id找到name，一起提交
			if (isCorrelationObj) {
				// 1 产品 产品的提交数据和备件物料不同
				if (relType === 1) {
					params.relObj = params.relObj.map(i => {
						return {
							relObjName: i.label,
							relObjId: i.key,
						}
					})
				} else {
					params.relObj = this.$refs.relationObjRef?.getIdAndName()
				}
				delete params.faultLabel
			} else {
				delete params.relObj
			}

			delete params.isCorrelationObj

			params.faultSource = this.faultSource

			return params
		},

		// 改变关联对象后触发
		relTypeChange() {
			[this.oldRelObj, this.ruleForm.relObj] = [this.ruleForm.relObj, this.oldRelObj]
		},
		chooseIcon(e) {
			this.ruleForm.attribute.iconImg.type = 0
			this.ruleForm.attribute.iconImg.index = e
			this.showChooseIcon = false
			this.$refs.uploadIconDom.setGoodsPicListBySystem(getListItem(e))
		},
		editIcon() {
			this.showChooseIcon = true
			this.$refs.changeIconDom.setData(this.ruleForm.attribute?.iconImg?.index || '0-0')
		},
		saveDesc(data) {
			this.ruleForm.faultDesc = data[i18n.locale];
			this.ruleForm.descNameLanguage = data;
		},
		saveContent(data) {
			this.ruleForm.faultContent = data[i18n.locale];
			this.ruleForm.contentNameLanguage = data;
		},
		saveLabel(data) {
			this.ruleForm.faultLabel = data[i18n.locale];
			this.ruleForm.labelNameLanguage = data;
		},
	},
}
</script>
<style lang="scss" scoped>
.icon-box {
	width: 80px;
	height: 80px;
	position: relative;
	&:hover {
		&::after {
			content: '+';
			background-color: rgba($color: #000000, $alpha: 0.6);
			position: absolute;
			width: 100%;
			height: 100%;
			left: 0;
			top: 0;
			font-size: 30px;
			color: #fff;
			line-height: 2.5;
			text-align: center;
			cursor: pointer;
		}
	}
	img {
		width: 100%;
		height: 100%;
	}
}
</style>

<style lang="scss">
.icon-file {
	.el-upload--picture-card {
		width: 80px;
		height: 80px;
		line-height: 88px;
	}
	.el-upload-list__item {
		width: 80px;
		height: 80px;
		margin-bottom: 0;
	}
	.el-upload__tip {
		line-height: 1.4;
	}
}
</style>
